import React, { useState } from "react";
import { Form, Input, Button, Checkbox } from "antd";
import { UserOutlined, LockOutlined, SafetyOutlined } from "@ant-design/icons";

import styled from "@emotion/styled";
import { useMount } from "hooks/useMount";
import { getCodeImg } from "api/login";
import { setPageTitle } from "store/actions/global";
import { handleLogin } from "store/actions/user";
import { useDispatch, useSelector } from "react-redux";
import { IStore } from "store";
import { useDocumentTitle } from "hooks/useDocumentTitle";
import { useHistory } from "react-router";

import bg from "../../assets/images/login-bg.jpg";

const Login = () => {
  useDocumentTitle("登录");
  const { title, userInfo } = useSelector((state: IStore) => {
    return Object.assign({}, state.userReducer);
  });
  const dispatch: any = useDispatch();
  const history = useHistory();
  const [form] = Form.useForm();
  const [codeHtml, setCodeHtml] = useState("");

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      console.log("Success:", values);
      await dispatch(handleLogin(values));
      console.log(userInfo);
      history.push("/layout/home");
    } catch (errorInfo) {
      console.log("Failed:", errorInfo);
    }
  };

  const getCode = () => {
    return getCodeImg().then((res) => {
      setCodeHtml(res as unknown as string);
    });
  };

  useMount(() => {
    getCode();
  });

  return (
    <LoginContainer>
      <LoginForm>
        <LoginTitle
          onClick={() => {
            dispatch(setPageTitle("新的标题"));
          }}
        >
          登录{title}
        </LoginTitle>
        <Form
          form={form}
          name="normal_login"
          className="login-form"
          initialValues={{ remember: true }}
        >
          <Form.Item
            name="userName"
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input
              prefix={<UserOutlined className="site-form-item-icon" />}
              placeholder="请输入用户名"
              size={"large"}
            />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: "请输入密码" }]}
          >
            <Input
              prefix={<LockOutlined className="site-form-item-icon" />}
              type="password"
              placeholder="请输入密码"
              size={"large"}
            />
          </Form.Item>
          <Form.Item
            name="captcha"
            rules={[{ required: true, message: "请输入验证码" }]}
          >
            <FormCaptcha>
              <Input
                prefix={<SafetyOutlined className="site-form-item-icon" />}
                placeholder="请输入验证码"
                size={"large"}
                style={{
                  width: "200px",
                }}
              />
              <Captcha
                className="captcha"
                dangerouslySetInnerHTML={{ __html: codeHtml }}
                onClick={getCode}
              ></Captcha>
            </FormCaptcha>
          </Form.Item>
          <Form.Item>
            <Form.Item name="remember" valuePropName="checked" noStyle>
              <Checkbox>记住密码？</Checkbox>
            </Form.Item>
          </Form.Item>

          <Form.Item>
            <Button block type="primary" onClick={handleSubmit}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </LoginForm>
    </LoginContainer>
  );
};

const LoginContainer = styled.div`
  display: flex;
  align-items: center;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  background-size: cover;
  box-sizing: border-box;
  justify-content: flex-end;
  background-image: url(${bg});
`;

const LoginForm = styled.div`
  width: 400px;
  box-sizing: border-box;
  padding: 20px 30px;
  border-radius: 4px;
  margin-right: 10%;
  background: #fff;
  box-shadow: 0 0 10px #999;
`;

const LoginTitle = styled.h3`
  text-align: center;
  font-size: 18px;
  line-height: 36px;
  font-weight: bold;
  margin-bottom: 15px;
`;

const FormCaptcha = styled.div`
  display: flex;
  align-items: center;
`;
const Captcha = styled.div`
  flex: 1;
  margin-left: 10px;
  height: 40px;
  svg {
    height: 40px;
  }
`;

export default Login;
